package com.axend.aerosense.base.utils;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

/**
 * 链式编程 简单封装Fragment切换
 * @author ChenHongWei
 * @date :2021/1/25 14:58
 */

public class FragmentManagerUtils {

    private static FragmentManagerUtils mInstance;
    private FragmentActivity fragmentActivity;
    private int containerId;
    private Fragment targetFragment;
    private Bundle bundle;
    private Fragment hideFragment;

    public static FragmentManagerUtils getInstance(){
        mInstance = new FragmentManagerUtils();
        return mInstance;
    }

    public FragmentManagerUtils setContext(FragmentActivity fragmentActivity){
        this.fragmentActivity = fragmentActivity;
        return mInstance;
    }

    //ContainerId
    public FragmentManagerUtils setContainerId(int containerId){
        this.containerId = containerId;
        return mInstance;
    }

    //目标Fragment
    public FragmentManagerUtils setTargetFragment(Fragment targetFragment){
        this.targetFragment = targetFragment;
        return mInstance;
    }

    public FragmentManagerUtils setArguments(Bundle bundle){
        this.bundle = bundle;
        return mInstance;
    }

    //当前需要隐藏的Fragment
    public FragmentManagerUtils hideFragment(Fragment hideFragment){
        this.hideFragment = hideFragment;
        return mInstance;
    }

    //提交
    public void commit(){
        if (fragmentActivity != null){
            FragmentTransaction fragmentTransaction = fragmentActivity.getSupportFragmentManager().beginTransaction();
            if (hideFragment != null){
                fragmentTransaction.hide(hideFragment);
            }
            if (bundle != null){
                targetFragment.setArguments(bundle);
            }
            fragmentTransaction.replace(containerId, targetFragment, targetFragment.getClass().getSimpleName());
            fragmentTransaction.commitAllowingStateLoss();
        }
    }



}
